package com.shqcjd.sinopecdemomobile.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.shqcjd.sinopecdemomobile.R;
import com.shqcjd.sinopecdemomobile.api.ApiService;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.sinopecdemomobile.model.ResponseData;
import com.shqcjd.sinopecdemomobile.model.pojo.AbnormalBean;
import com.shqcjd.sinopecdemomobile.model.pojo.ImgBean;
import com.shqcjd.sinopecdemomobile.model.pojo.UploadException;
import com.shqcjd.sinopecdemomobile.ui.adapter.AbnormalAdapter;
import com.shqcjd.sinopecdemomobile.ui.base.BaseActivity;
import com.shqcjd.sinopecdemomobile.ui.base.BasePresenter;
import com.shqcjd.sinopecdemomobile.util.AlbumUtils;
import com.shqcjd.sinopecdemomobile.util.MyGlideEngine;
import com.shqcjd.sinopecdemomobile.util.ToastUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class AbnormalActivity extends BaseActivity {
    @BindView(R.id.tv_dialog_abnormal)
    TextView tvDialogAbnormal;
    @BindView(R.id.et_dialog_abnormal)
    EditText etDialogAbnormal;
    @BindView(R.id.rv_dialog_abnormal)
    RecyclerView rvDialogAbnormal;
    @BindView(R.id.btn_submit)
    Button btnSubmit;
    @BindView(R.id.tv_include_title)
    TextView tvIncludeTitle;
    @BindView(R.id.tv_include_finish)
    Button tvIncludeFinish;
    private Context context;
    private AbnormalAdapter dialogAbnormalAdapter;
    private List<ImgBean> mList = new ArrayList<>();
    private final int IMAGE_FILE_RESULT_CODE = 2;
    private static final int REQUEST_ABNORMAL_CODE = 119;

    private int tId, epId, eId, prid;
    private String value;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_abnormal;
    }

    @Override
    public void init() {
        super.init();
        context = this;
        tId = getIntent().getIntExtra("tId", 0);
        epId = getIntent().getIntExtra("epId", 0);
        eId = getIntent().getIntExtra("eId", 0);
        prid = getIntent().getIntExtra("prid", 0);
        value = getIntent().getStringExtra("value");
    }

    @Override
    public void initView() {
        super.initView();
        tvIncludeTitle.setText("巡检异常");
        dialogAbnormalAdapter = new AbnormalAdapter(mList, context);
        rvDialogAbnormal.setLayoutManager(new GridLayoutManager(context, 4));
        rvDialogAbnormal.setAdapter(dialogAbnormalAdapter);

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mList.size() > 0) {
                    loadMultiFile(mList);
                } else {
                    List<String> l = new ArrayList<>();
                    putExceptionInfo(l);
                    Toast.makeText(context, "请上传异常图片", Toast.LENGTH_SHORT).show();
                }
            }
        });

        dialogAbnormalAdapter.setOnClickDialogListener(new AbnormalAdapter.setOnClickItemAdapterListener() {
            @Override
            public void onClickAddPic(int pos) {
                RequestLocationAndCallPermission();
            }

            @Override
            public void onClickDeletePic(int pos) {
                deletePic(pos);
            }
        });

        tvIncludeFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        getAbnormalInfoHttp(tId, epId, eId, value);
    }

    private void getAbnormalInfoHttp(int task_id, int equipment_id, int equipment_part_item_id, String value) {
        ApiService.getAbnormalInfo(task_id, equipment_id, equipment_part_item_id, value)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<AbnormalBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<AbnormalBean> responseData) {
                        if (responseData.retCode == 10000) {
                            List<ImgBean> list = new ArrayList<>();
                            for (int i = 0; i < responseData.data.imgs.size(); i++) {
                                list.add(new ImgBean(responseData.data.imgs.get(i), false));
                            }
                            if(!responseData.data.solution_description.equals("")){
                                tvDialogAbnormal.setText("常见异常提醒\n●" + responseData.data.solution_description);
                            }
                            mList.addAll(list);
                            dialogAbnormalAdapter.notifyDataSetChanged();
                            etDialogAbnormal.setText(responseData.data.exception_description);
                        } else {
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        Toast.makeText(context, "网络连接异常", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    /**
     * 上传多图
     *
     * @param mList
     */
    private void loadMultiFile(List<ImgBean> mList) {
        //上传图片的时候  把本地图片拿出来上传  然后上传成功之后 把上传成功的图片和网络图片合体
        List<File> files = new ArrayList<>();
        for (ImgBean uri : mList) {
            if (uri.isLocal) {
                files.add(new File(uri.url));
            }
        }
        if (files.size() == 0) {
            List<String> l = new ArrayList<>();
            for (int i = 0; i < mList.size(); i++) {
                if (!mList.get(i).isLocal) {
                    l.add(mList.get(i).url);
                }
            }
            putExceptionInfo(l);
        } else {
            ApiService.uploadMultiImg(files)
                    .compose(RxSchedulersHelper.io_main())
                    .subscribe(new RxObserver<ResponseData<List<String>>>() {
                        @Override
                        public void _onSubscribe(Disposable d) {
                            super._onSubscribe(d);
                            showWaitingDialog("上传图片中");
                        }

                        @Override
                        public void _onNext(ResponseData<List<String>> retData) {
                            if (retData.retCode == 10000) {
                                List<String> list = retData.data;
                                for (int i = 0; i < mList.size(); i++) {
                                    if (!mList.get(i).isLocal) {
                                        list.add(mList.get(i).url);
                                    }
                                }
                                putExceptionInfo(list);
                            } else {
                                ToastUtils.showShort(context, "上传失败");
                            }
                        }

                        @Override
                        public void _onError(String errorMessage) {
                            hideWaitingDialog();
                            ToastUtils.showShort(context, errorMessage);
                        }

                        @Override
                        public void _onComplete() {
                            super._onComplete();
                            hideWaitingDialog();
                        }
                    });
        }

    }

    /**
     * 添加或修改巡检异常描述
     *
     * @param data
     */
    private void putExceptionInfo(List<String> data) {
        String info = etDialogAbnormal.getText().toString();
        UploadException uploadException = new UploadException();
        uploadException.patrol_record_id = prid;
        uploadException.info = info;
        uploadException.imgs = data;
        String json = new Gson().toJson(uploadException);

        ApiService.putCheckException(json)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<String>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在上传异常信息");
                    }

                    @Override
                    public void _onNext(ResponseData<String> retData) {
                        if (retData.retCode == 10000) {
                            ToastUtils.showShort(context, "提交成功");
                            Intent it = new Intent();
                            it.putExtra("finish", true);
                            setResult(REQUEST_ABNORMAL_CODE, it);
                            finish();
                        } else {
                            ToastUtils.showShort(context, "提交信息失败");
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(context, errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    public void RequestLocationAndCallPermission() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(
                Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            Matisse.from(AbnormalActivity.this)
                                    .choose(MimeType.ofImage()) // 选择 mime 的类型
                                    .countable(false)
                                    .maxSelectable(6) // 图片选择的最多数量
                                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                    .thumbnailScale(0.85f) // 缩略图的比例
                                    .imageEngine(new MyGlideEngine()) // 使用的图片加载引擎
                                    .theme(R.style.Matisse_Zhihu)
                                    .capture(true)//选择照片时，是否显示拍照
                                    .captureStrategy(new CaptureStrategy(true, getPackageName()))//参数1 true表示拍照存储在共有目录，false表示存储在私有目录；参数2与 AndroidManifest中authorities值相同，用于适配7.0系统 必须设置
                                    .forResult(IMAGE_FILE_RESULT_CODE); // 设置作为标记的请求码
                        } else {

                        }
                    }
                });
    }

    public void addPic(ImgBean uri) {
        mList.add(uri);
        dialogAbnormalAdapter.notifyDataSetChanged();
    }

    public void deletePic(int pos) {
        mList.remove(pos);
        dialogAbnormalAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IMAGE_FILE_RESULT_CODE && resultCode == RESULT_OK) {
            //图片上传
            if (data != null) {
                List<Uri> uris = Matisse.obtainResult(data);
                for (Uri uri : uris) {
                    try {
                        String albumStringPath = AlbumUtils.getRealFilePath(this, uri);
                        addPic(new ImgBean(albumStringPath, true));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }

}
